package org.stars.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * Contiene delle funzione d'utilità per i file. I metodi contenuti in questa
 * classe sono metodi statici.
 * 
 * @author Francesco Benincasa (908099)
 */
public class FileUtility {

	/**
	 * Data una stringa che rappresnta un percorso, cerca di renderlo uniforme
	 * convertendo tutte le barre backslash (\), doppie backslash le doppie
	 * slash (//) in un path contenente solo slash (/).
	 * 
	 * @param oldPath
	 *            path da correggere
	 * @return path il cui unico separatore è /
	 */
	public static String adjustPath(String oldPath) {
		String temp=String.valueOf(File.separatorChar);
		oldPath = StringUtility.nvl(oldPath);
		
		oldPath = StringUtility.replace(oldPath, "\\",temp );
		oldPath = StringUtility.replace(oldPath, "\\",temp);

		// lo facciamo due volte per gestire i casi anche con triplo slash
		oldPath = StringUtility.replace(oldPath, "//", temp);
		oldPath = StringUtility.replace(oldPath, "//", temp);
		
		oldPath = StringUtility.replace(oldPath, "/",temp );
		return oldPath;
	}

	/**
	 * Recupera il path di base da dove stiamo eseguendo l'applicazione.
	 * 
	 * @return la stringa che rappresenta il path. Il path non contiene il
	 *         backslash finale
	 */
	public static String getBasePath() {
		String sBasePath = new File("").getAbsolutePath();

		return sBasePath;
	}

	/**
	 * Verifica la presenza di un file sul file system. Ritorna <i>true</i> se
	 * il file esiste, <i>false</i> altrimenti.
	 * 
	 * @param sFileName
	 *            nome del file
	 * @return restituisce <i>true</i> se il file esiste, <i>false</i>
	 *         altrimenti.
	 */
	public static boolean existsFile(String sFileName) {
		boolean bResult;
		try {
			File f = new File(sFileName);
			bResult = f.exists();
		} catch (Exception e) {
			bResult = false;
		}
		return bResult;

	}

	/**
	 * Write into <code>destFileName</code> the list of strings.
	 * 
	 * @param destFileName
	 * @param lines
	 * @throws IOException
	 */
	public static void writeStringList(String destFileName, List<String> lines) throws IOException {
		writeStringList(destFileName, lines, false);
	}

	public static void writeStringList(String destFileName, List<String> lines, boolean append) throws IOException {
		BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(new File(destFileName), append));
		byte[] buffer;
		int size;
				
		for (String item : lines) {
			buffer=item.getBytes();
			size=buffer.length;
			fos.write(buffer, 0, size);
		}
		fos.close();
	}

	public static void writeString(String destFileName, String lines) throws IOException {
		writeString(destFileName, lines, false);
	}

	public static void writeString(String destFileName, String lines, boolean append) throws IOException {
		BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(new File(destFileName), append));

		byte[] buffer=lines.getBytes();
		
		fos.write(buffer,0, buffer.length);

		fos.close();
	}

	public static void writeBytes(String destFileName, byte[] buffer, boolean append) throws IOException {
		BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(new File(destFileName), append));
		fos.write(buffer,0, buffer.length);
		fos.close();
	}

	public static void writeBytesIntoFile(String strFilePath, byte[] buffer) throws IOException {
		writeBytes(strFilePath, buffer, false);
	}

	public static void writeFile(String destFileName, String srcFileName) throws IOException {
		writeFile(destFileName, srcFileName, false);
	}

	public static void writeFile(String destFileName, String srcFileName, boolean append) throws IOException {
		byte[] buffer = new byte[64 * 1024];

		BufferedInputStream fis = new BufferedInputStream(new FileInputStream(srcFileName));
		BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(new File(destFileName), append));

		int rb;

		while ((rb = fis.read(buffer)) != -1) {
			fos.write(buffer, 0, rb);
		}

		fis.close();
		fos.close();
	}

	public static byte[] readBytes(String srcFileName) throws IOException {
		File file = new File(srcFileName);
		BufferedInputStream is = new BufferedInputStream(new FileInputStream( file));

		// Get the size of the file
		long length = file.length();

		if (length > Integer.MAX_VALUE) {
			// File is too large
		}

		// Create the byte array to hold the data
		byte[] bytes = new byte[(int) length];

		// Read in the bytes
		int offset = 0;
		int numRead = 0;
		while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
			offset += numRead;
		}

		// Ensure all the bytes have been read in
		if (offset < bytes.length) {
			throw new IOException("Could not completely read file " + file.getName());
		}

		// Close the input stream and return bytes
		is.close();

		return bytes;
	}
}

/* -- EOF -- */